package com.xiao.xin.core.service.Impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.xin.core.Mapper.UserMapper;
import com.xiao.xin.core.Util.JwtUtil;
import com.xiao.xin.core.domain.UserResult;
import com.xiao.xin.core.dto.UserLoginDto;
import com.xiao.xin.core.exception.UserLoginException;
import com.xiao.xin.core.domain.User;
import com.xiao.xin.core.service.UserService;
import com.xiao.xin.core.vo.UserLoginResponseVo;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /***
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public UserLoginResponseVo login(UserLoginDto dto) {
        if (StrUtil.isBlank(dto.getUsername()) || StrUtil.isBlank((dto.getPassword()))) {
            throw new UserLoginException("账号或密码错误，请重新输入");
        }

        User user = getOne(Wrappers.
                <User>lambdaQuery()
                .eq(User::getUsername, dto.getUsername()).or()
                .eq(User::getMobile, dto.getUsername())
        );
        if (ObjUtil.isEmpty(user) || !BCrypt.checkpw(dto.getPassword(), user.getPassword()))
            throw new UserLoginException("账号或密码错误，请重新输入");

        return UserLoginResponseVo
                .builder()
                .id(user.getId())
                .name(user.getNickname())
                .avatar(user.getAvatar())
                .token(JwtUtil.generateToken(User
                        .builder()
                        .id(user.getId())
                        .username(user.getUsername())
                        .build()))
                .build();
    }

}
